package com.ty.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ty.entity.Book;
import com.ty.mapper.BookMapper;
import com.ty.resp.CommonResp;
import com.ty.service.IBookService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by IntelliJ IDEA.
 *
 * @author : txy
 * @create : 2024/1/9 13:42
 */
@Service
public class BookServiceImpl extends ServiceImpl<BookMapper, Book> implements IBookService {
    @Resource
    private BookMapper pm;

    public CommonResp queryAll(Page<Book> page, String orderBy, String search) {
        CommonResp resp = new CommonResp();
        //是否要根据指定字段排序,目前系统的首页用到了排序，按照销量取前5
        if (StringUtils.hasText(orderBy)) {
            QueryWrapper wrapper = new QueryWrapper();
            wrapper.orderByDesc(orderBy);
            List<Book> list = baseMapper.selectList(new Page<>(1, 5), wrapper);
            ArrayList<HashMap<String, String>> maps = new ArrayList<>();
            list.forEach((book) -> {
                HashMap<String, String> map = new HashMap<>();
                map.put("value", String.valueOf(book.getSalesNum()));
                map.put("name", book.getName());
                maps.add(map);
            });
            resp.setContent(maps);
        } else {
            QueryWrapper<Book> wrapper = new QueryWrapper<>();
            //是否带有搜索条件
            if (StringUtils.hasText(search)) {
                wrapper.like("name", search);
            }
            Page<Book> books = baseMapper.selectAllBooks(page, wrapper);
            resp.setContent(books);
        }
        return resp;
    }

    @Override
    public Page<Book> queryByType(Page<Book> page, String name, Integer typeId) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        QueryWrapper<Book> eq = wrapper.like("name", name).eq("type", typeId);
        return pm.selectPage(page, eq);
    }

    @Override
    public Page<Book> queryByName(Page<Book> page, String name) {
        QueryWrapper<Book> wrapper = new QueryWrapper<>();
        QueryWrapper<Book> queryWrapper = wrapper.like("name", name);
        return pm.selectPage(page, queryWrapper);
    }

    @Override
    public Book queryById(Integer id) {
        //QueryWrapper<PeriodicalEntity> wrapper = new QueryWrapper<>();
        //QueryWrapper<PeriodicalEntity> queryWrapper = wrapper.eq("id", id);
        return pm.selectById(id);
    }

    @Override
    public List<HashMap<String, String>> getBooksByNum(Integer num) {
        if (num == null) {
            num = 20;
        }
        return pm.selectBooks(num);
    }


}
